#include"head.h"
#include"add_friends.h"
#define LOGPORT 50021
#define COMPORT 50022
// pthread_mutex_t userMutex = PTHREAD_MUTEX_INITIALIZER;
struct sockaddr_in srvAddr;
static int sockfd;
static void conncet_server(char *ip,const char *name);
static void logout(int sig);
static void *sendMsg(void *arg);
static void *recvMsg(void *arg);
static void jiemian(void);
static void login(void);
static void register_user(void);

static void logout(int sig)
{
    // 登出
    int logfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    srvAddr.sin_port = htons(LOGPORT);
    Connect(logfd,(struct sockaddr *)&srvAddr,sizeof(struct sockaddr_in));
    send(logfd, "out", 3, 0);  
    srvAddr.sin_port = htons(COMPORT);
    close(sockfd);
    close(logfd);
    exit(0);
}

static void *sendMsg(void *arg)
{
    char buf[256];
    while(1)
    {
        bzero(buf, sizeof(buf));
        fgets(buf, sizeof(buf), stdin);
        if(send(sockfd, buf, strlen(buf), 0)<0)
        {
            perror("send erron");
        } 
    }
}

static void *recvMsg(void *arg)
{
    char buf[256];
    while (1)
    {
        bzero(buf, sizeof(buf));
        int n = recv(sockfd, buf, sizeof(buf) - 1, 0); 
        if (n <= 0) break;
        buf[n] = '\0';

        // 如果收到的是 "[私聊]" 开头的内容，判断为私聊消息
        if ((strstr(buf, "[私聊]") != NULL)
    )
        {
            printf("%s", buf); // 私聊格式，直接打印
        }
        else
        {
            printf("群消息：%s", buf); // 默认群发格式
        }
    }
}


static void jiemian(void)
{
    printf("=======1.登录用户=======\n");
    printf("=======2.注册账号=======\n");
}

static void login(void)
{
    int cnt = 0;
    char name[20] ;
    char password[20];
    while (1)
    {
    printf("请输入账号:\n");
    scanf("%s",name);
    printf("请输入密码:\n");
    scanf("%s",password);
    user_create();
    user_load(head1,USER_FILE);                                            
    if (user_login(head1,name,password) == 1)
    {
        
        // printf("请输入服务器ip地址");
        // char ip[20] = {0};
        // scanf("%s",ip);
        conncet_server("192.168.3.69",name);
        printf("退出登录!\n");
        break;
    }
    else 
    {
        printf("用户或密码错误\n");
        if ((cnt++) == 2)
        {
            break;
        }
    }
    }
    jiemian();
    
}
static void register_user(void)
{
    int cnt = 0;
    char name[20];
    char password[20];
    char repassword[20];
    while (1)
    {
    printf("请输入账号:\n");
    scanf("%s",name);
    printf("请输入密码:\n");
    scanf("%s",password);
    printf("请确认密码:\n");
    scanf("%s",repassword);
    user_create();
    if (user_register(head1,name,password))
    {
        printf("注册成功!\n");
        user_save(head1,USER_FILE);
        break;
    }
    else
    {
        if (strcmp(password,repassword) != 0)
        {
            printf("两次密码输入不一致！\n");
        }
        if (!user_register(head1,name,password))
        {
            printf("用户名已存在！\n");
        }
        if ((cnt++) == 2)
        {
            break;
        }
    
    }
    }
    jiemian();
}
static void conncet_server(char *ip,const char *name)
{
    
    sockfd = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    int logfd = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    srvAddr.sin_family = AF_INET;
    srvAddr.sin_addr.s_addr = inet_addr(ip); // 服务器IP
    srvAddr.sin_port = htons(LOGPORT);
    Connect(logfd,(struct sockaddr *)&srvAddr,sizeof(struct sockaddr_in));
    send(logfd, "in", 2, 0);
    close(logfd);
   // 登入
   srvAddr.sin_port = htons(COMPORT);
   Connect(sockfd,(struct sockaddr *)&srvAddr,sizeof(struct sockaddr_in));
   send(sockfd, name, strlen(name), 0);

    // 设置非阻塞检测登录状态
    int flags = fcntl(sockfd, F_GETFL, 0);
    fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
    
    // 等待1秒看是否有登录错误
    struct timeval tv = {1, 0};
    fd_set rfds;
    FD_ZERO(&rfds);
    FD_SET(sockfd, &rfds);
    
    if (select(sockfd+1, &rfds, NULL, NULL, &tv) > 0) 
    {
        char reply[128] = {0};
        int n = recv(sockfd, reply, sizeof(reply)-1, 0);
        if (n > 0 && strstr(reply, "该用户名已登录")) 
        {
            printf("%s\n", reply);
            close(sockfd);
            return;
        }
    }
    
    // 恢复阻塞模式
    fcntl(sockfd, F_SETFL, flags);
     printf("登录成功！\n");
   // 登出准备
   signal(SIGINT, logout);

   // 进入收发消息线程
   pthread_t t1, t2;
   srvAddr.sin_port = htons(COMPORT);
   pthread_create(&t1, NULL, sendMsg, NULL);
   pthread_create(&t2, NULL, recvMsg, NULL);

   pthread_join(t1, NULL);
   pthread_join(t2, NULL);
}

int main(void)
{
    jiemian();
    int choice ;
    while (1)
    {
        scanf("%d",&choice);
        switch (choice)
        {
        case 1:login();break;
        
        case 2:register_user();break;
        case 0:break;
        }
        if (choice == 0)
        {
            break;
        }
    }
}